package com.java80.littlegame.service.game.desk;

import java.util.List;
import java.util.Timer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.java80.littlegame.common.base.data.GameUser;
import com.java80.littlegame.common.base.data.GameUserMgr;
import com.java80.littlegame.common.base.vertx.VertxMessageHelper;
import com.java80.littlegame.common.msg.BaseMsg;
import com.java80.littlegame.common.msg.cluster.ClusterMessage;
import com.java80.littlegame.common.msg.cluster.DeskEndMessage;
import com.java80.littlegame.common.msg.timer.TimerMessage;
import com.java80.littlegame.service.game.GameConfig;

public abstract class Desktop {
	protected DeskSetting setting;
	protected boolean DesktopRun;
	private Timer timer;
	final transient static Logger log = LoggerFactory.getLogger(Desktop.class);

	public Desktop(DeskSetting setting) {
		super();
		this.setting = setting;
		this.DesktopRun = true;
		this.timer=new Timer();
	}

	/**
	 * 启动一局游戏
	 */
	public abstract void onStart();

	/**
	 * 接收客户端消息
	 */
	public abstract void onMessage(long userId, BaseMsg msg);

	/**
	 * 系统消息
	 */
	public abstract void onClusterMessage(ClusterMessage msg);

	/**
	 * 给局内玩家发消息
	 * 
	 * @param msg
	 */
	public void broadcastMessage(BaseMsg msg) {
		List<Long> playerIds = setting.getPlayerIds();
		for (Long id : playerIds) {
			sendMessage(id, msg);
		}
	}

	/**
	 * 给局内玩家发消息
	 * 
	 */
	public void sendMessage(long userId, BaseMsg msg) {
		GameUser gameUser = GameUserMgr.getGameUser(userId);
		msg.setSessionId(null);
		msg.setRecUserId(userId);
		log.debug("send msg -> {},{}", gameUser, msg);
		VertxMessageHelper.sendMessageToGateWay(gameUser, msg);
	}

	public void endDesk() {
		DeskEndMessage end = new DeskEndMessage();
		int roomId = setting.getRoomId();
		end.setRoomId(roomId);
		VertxMessageHelper.sendMessageToService(GameConfig.getQueueName(), end.toString());
	}
	/**定时器回调*/
	public abstract void onTimer(TimerMessage msg);
	/**增加游戏局内的定时任务，比如等待时间等等*/
	public void addTask(TimerMessage msg){
		DeskTask deskTask = new DeskTask(msg, this);
		timer.schedule(deskTask, msg.getDelay());
	}

	public DeskSetting getSetting() {
		return setting;
	}

	public void setSetting(DeskSetting setting) {
		this.setting = setting;
	}
}
